const jwt = require('jsonwebtoken');
const { pool } = require("../config/database");
const logger = require('../utils/logger');
const LoginLogService = require('./login-log.service');

class AuthService {
  /**
   * 用户登录
   * @param {string} username 用户名
   * @param {string} password 密码
   * @param {Object} clientInfo 客户端信息
   * @param {string} clientInfo.ip IP地址
   * @param {string} clientInfo.userAgent 用户代理
   */
  static async login(username, password, clientInfo) {
    try {
      // 查询用户
      const [users] = await pool.query(
        'SELECT * FROM users WHERE username = ? AND status = 1',
        [username]
      );

      const user = users[0];
      
      // 记录登录日志的基础数据
      const logData = {
        userId: user?.id || 0,
        username,
        ip: clientInfo.ip,
        userAgent: clientInfo.userAgent,
        success: false
      };

      // 用户不存在
      if (!user) {
        logData.failReason = '用户不存在';
        await LoginLogService.create(logData);
        throw new Error('用户名或密码错误');
      }

      // 验证密码（明文比较）
      if (password !== user.password) {
        logData.failReason = '密码错误';
        await LoginLogService.create(logData);
        throw new Error('用户名或密码错误');
      }

      // 生成token
      const accessToken = jwt.sign(
        { id: user.id, username: user.username },
        process.env.JWT_SECRET,
        { expiresIn: parseInt(process.env.JWT_ACCESS_EXPIRATION) }
      );

      const refreshToken = jwt.sign(
        { id: user.id, username: user.username },
        process.env.JWT_SECRET,
        { expiresIn: parseInt(process.env.JWT_REFRESH_EXPIRATION) }
      );

      // 更新最后登录时间
      await pool.query(
        'UPDATE users SET last_login = NOW() WHERE id = ?',
        [user.id]
      );

      // 记录成功登录日志
      logData.success = true;
      await LoginLogService.create(logData);

      // 获取最近的登录记录
      const recentLogs = await LoginLogService.getRecentLogs(user.id);

      return {
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          status: user.status,
          lastLogin: user.last_login
        },
        accessToken,
        refreshToken,
        recentLogs
      };
    } catch (error) {
      logger.error('登录失败:', error);
      throw error;
    }
  }

  /**
   * 刷新访问令牌
   * @param {string} refreshToken 刷新令牌
   */
  static async refreshToken(refreshToken) {
    try {
      const decoded = jwt.verify(refreshToken, process.env.JWT_SECRET);
      
      // 验证用户是否存在且状态正常
      const [users] = await pool.query(
        'SELECT id, username, status FROM users WHERE id = ? AND status = 1',
        [decoded.id]
      );

      const user = users[0];
      if (!user) {
        throw new Error('用户不存在或已被禁用');
      }

      // 生成新的访问令牌
      const accessToken = jwt.sign(
        { id: user.id, username: user.username },
        process.env.JWT_SECRET,
        { expiresIn: parseInt(process.env.JWT_ACCESS_EXPIRATION) }
      );

      return { accessToken };
    } catch (error) {
      logger.error('刷新令牌失败:', error);
      throw error;
    }
  }

  /**
   * 登出
   * @param {number} userId 用户ID
   */
  static async logout(userId) {
    // 这里可以实现令牌黑名单等逻辑
    return true;
  }
}

module.exports = AuthService; 